package main

import (
	"bytes"
	"fmt"
	"os/exec"
	"runtime"
)

func ping(host string) (bool, error) {
	var cmd *exec.Cmd

	switch runtime.GOOS {
	case "windows":
		cmd = exec.Command("ping", "-n", "1", host)
	case "linux", "darwin":
		cmd = exec.Command("ping", "-c", "1", host)
	default:
		return false, fmt.Errorf("unsupported platform")
	}

	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return false, err
	}

	// 检查输出中是否包含 "ttl" 或 "TTL"（Linux/Windows）
	if bytes.Contains(out.Bytes(), []byte("ttl=")) ||
		bytes.Contains(out.Bytes(), []byte("TTL=")) {
		return true, nil
	}

	return false, nil
}

func main() {
	host := "172.168.3.21"
	reachable, err := ping(host)
	if err != nil {
		fmt.Printf("Error pinging %s: %v\n", host, err)
		return
	}

	if reachable {
		fmt.Printf("%s is reachable\n", host)
	} else {
		fmt.Printf("%s is not reachable\n", host)
	}
}
